<template>
  <div class="main">
    <div class="leftTree">
      <el-tree :data="treeData" :props="defaultProps" default-expand-all :expand-on-click-node="false" accordion @node-click="handleNodeClick" />
    </div>
    <div class="app-container">
      <div class="contentDiv">
        <div class="tx-r" style="margin-bottom:10px">
          <el-button v-permiss="['60202280']" size="small" type="primary" round style="float:right;margin-left:10px" @click="showImport">导入</el-button>
          <el-button v-permiss="['60202220']" size="small" type="primary" round @click="handleAdd">新增</el-button>
        </div>
        <el-table :key="tableKey" v-loading="listLoading" :data="tableData" fit highlight-current-row style="width: 100%;" size="small" row-key="id">
          <el-empty slot="empty" :image-size="120" description="暂无数据" />

          <el-table-column label="序号" type="index" width="50" align="center" />
          <el-table-column label="客户类别代码" align="center">
            <template slot-scope="{row}">
              <span>{{ row.custTypeCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="客户类别名称" align="center">
            <template slot-scope="{row}">
              <span>{{ row.custTypeName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center">
            <template slot-scope="{row}">
              <span>{{ row.remarks }}</span>
            </template>
          </el-table-column>
          <el-table-column label="是否启用" align="center">
            <template slot-scope="{row}">
              <el-switch v-model="row.isDisable" :active-value="0" :inactive-value="1" @change="updateStatus($event, row)" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="220">
            <template slot-scope="{row}">
              <el-button v-permiss="['60202230']" type="text" size="small" @click="handleCompile(row)">编辑</el-button>
              <el-button v-permiss="['60202260']" type="text" size="small" @click="handleDel(row.id)">删除</el-button>
              <el-button v-if="row.leaf==1" v-permiss="['60202270']" type="text" size="small" @click="handleAssign(row)">分配客户</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-dialog :close-on-click-modal="false" :title="dialogStatus=='create'?'新增客户类别':'修改客户类别'" :visible.sync="dialogVisible" width="460px">
        <el-form ref="dataForm" :rules="rules" :model="form" label-position="right" label-width="110px" style="width: 400px; margin-left:10px;">
          <el-form-item label="客户类别代码" prop="custTypeCode">
            <el-input v-model="form.custTypeCode" placeholder="客户类别代码" />
          </el-form-item>
          <el-form-item label="客户类别名称" prop="custTypeName">
            <el-input v-model="form.custTypeName" placeholder="客户类别名称" />
          </el-form-item>
          <el-form-item label="上级类别" prop="parentId">
            <treeselect v-model="form.parentId" :options="treeData" :normalizer="normalizer" placeholder="选择上级类别" />
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="form.remarks" placeholder="备注" />
          </el-form-item>
          <el-form-item label="是否启用" prop="isDisable">
            <el-radio v-model="form.isDisable" :label="0">是</el-radio>
            <el-radio v-model="form.isDisable" :label="1">否</el-radio>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" align="center">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="dialogStatus == 'create'?handleCreate():handleModify()">确定</el-button>
        </div>
      </el-dialog>
      <assignCust ref="custTable" :tit="handleObj.custTypeName + handleObj.custTypeCode" :show-modal.sync="showModal" type="custType" :handle-obj="handleObj" @handleAssign="handleAssignCust" />
    </div>
    <import-data ref="importRef" type="custType" title="客户类别" />
  </div>
</template>
<script>
import { saveCustType, delCustType, getCustTypeTree, updateCustTypeDisabled, getCustTypeTreeDataByParentId, updateCustTypeIdByCustIdList } from '@/api/basedata'
import assignCust from '@/components/assignCust'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import importData from './importData'
export default {
  name: 'BaseCustType',
  components: { assignCust, Treeselect, importData },
  data() {
    return {
      tableKey: 0,
      tableData: [],
      custList: [],
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'custTypeName'
      },
      handleObj: {},
      selectIdArr: [],
      total: 0,
      listLoading: true,
      showModal: false,
      parentId: null,
      form: {
        id: '',
        custTypeName: '',
        custTypeCode: '',
        remarks: '',
        parentId: null,
        isDisable: 0
      },
      resetform: {
        id: '',
        custTypeName: '',
        custTypeCode: '',
        remarks: '',
        parentId: '',
        isDisable: 0
      },
      dialogVisible: false,
      dialogStatus: '',
      rules: {
        custTypeName: [{ required: true, message: '名称不能为空', trigger: 'change' }],
        custTypeCode: [{ required: true, message: '代码不能为空', trigger: 'change' }],
        parentId: [{ required: true, message: '上级类别不能为空', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getList()
    this.getLeftTree()
  },
  methods: {
    showImport() {
      this.$refs.importRef.option = {
        show: true
      }
    },
    getLeftTree() {
      getCustTypeTree({ parentId: null, includeRoot: 0 }).then(res => {
        this.treeData = res.data.data || []
        this.treeData[0].id = 0
      }).catch(() => {
        this.listLoading = false
      })
    },
    normalizer(node) {
      if (!node.children || (node.children && !node.children.length)) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.custTypeName,
        children: node.children
      }
    },
    handleNodeClick(e) {
      this.parentId = e.id
      this.getList()
    },
    handleAssign(row) {
      this.showModal = true
      this.handleObj = row
    },
    handleAssignCust(arr) {
      var obj = {
        custTypeId: this.handleObj.id,
        custIdList: arr
      }
      updateCustTypeIdByCustIdList(obj).then(res => {
        if (res.data.errorCode === '0') {
          this.$refs.custTable.closeModal()
          this.getList()
          this.$message.success(res.data.msg)
        }
      })
    },
    getList() {
      this.listLoading = true
      getCustTypeTreeDataByParentId({ parentId: this.parentId || null, includeRoot: 0 }).then(res => {
        this.listLoading = false
        this.tableData = res.data.data || []
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleAdd() {
      this.dialogVisible = true
      this.dialogStatus = 'create'
      for (var key in this.form) {
        this.form[key] = this.resetform[key]
      }
      this.form.parentId = this.parentId || null
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleCompile(obj) {
      this.dialogVisible = true
      this.dialogStatus = 'update'
      for (var key in this.form) {
        this.form[key] = obj[key]
      }
      this.form.parentId = obj.parentId || null
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleFilter() {
      this.getList()
    },
    handleDel(id) {
      this.$confirm('确定删除？', '提示', {
        confirmButtonText: '确定',
        closeOnClickModal: false,
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delItem(id)
      })
    },
    updateStatus(e, row) {
      this.changeAvaiable(e, row.id)
    },
    changeAvaiable(isDisable, id) {
      var obj = { isDisable, id }
      updateCustTypeDisabled(obj).then(res => {
        if (res.data.errorCode === '0') {
          this.$message.success(res.data.msg)
        }
      })
    },
    handleModify() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          saveCustType(this.form).then(res => {
            if (res.data.errorCode === '0') {
              this.getList()
              this.getLeftTree()
              this.dialogVisible = false
              this.$message.success(res.data.msg)
            }
          }).catch(() => {
            this.$message.error('系统错误')
          })
        }
      })
    },
    handleCreate() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.form.parentId = this.parentId
          saveCustType(this.form).then(res => {
            if (res.data.errorCode === '0') {
              this.getList()
              this.getLeftTree()
              this.dialogVisible = false
              this.$message.success(res.data.msg)
            }
          }).catch(() => {
            this.$message.error('系统错误')
          })
        }
      })
    },
    delItem(id) {
      delCustType(id).then(res => {
        if (res.data.errorCode === '0') {
          this.getList()
          this.getLeftTree()
          this.dialogVisible = false
          this.$message.success(res.data.msg)
        }
      })
    }
  }
}
</script>
<style scoped>
.curTit {
    font-size: 14px;
    margin-bottom: 10px
}
.main {
    position: relative;
    width: 100%;
    height: 100%;
    padding-left: 180px;
}
.leftTree {width: 170px;height: 100%;background-color: #fff;position: absolute;top: 10px;left: 10px;border:1px #eee solid;}

.tableDiv {
    width: 100%;
}
.fileDiv {
  width: 400px;
  height: 60px;
  border: 1px #d0d0d0 solid;
  line-height: 60px;
  text-align: center;
  border-radius: 6px;
}
.filter-item {
  position: relative;
}
</style>
